package com.qf.shop.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class MyInter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String uri = request.getRequestURI();

        HttpSession session = request.getSession();
        // 获取用户在登录成功之后设置的用户信息
        Object object = session.getAttribute("user");
        if(null != object) {
            return true;
        }

        //4.cookie放行
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("userId".equals(cookie.getName())) {
                    if (null != cookie.getValue()) {
                        System.out.println("value:::"+cookie.getValue());
                        return true;
                    }
                }
            }
        }
//        response.sendRedirect("http://localhost:8080/shop/login.html");
//        if("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
//            //告诉ajax我是重定向
//            response.setHeader("REDIRECT", "REDIRECT");
//            //告诉ajax我重定向的路径
//            response.setHeader("CONTENTPATH", "shop/login.html");
//            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
//        }else{
//            response.sendRedirect(  "shop/login.html");
//        }
        response.sendRedirect(  "shop/login.html");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        System.out.println("fjio");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
